package cn.aishua.ui.myKaka;

import java.util.Calendar;
import java.util.List;

import org.apache.http.HttpResponse;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import cn.aishua.data.DatabaseOperator;
import cn.aishua.network.HttpRequestUtil;
import cn.aishua.ui.MainActivityGroup;
import cn.aishua.ui.myKaka.task.DataExchangeAsyncTask;
import cn.aishua.util.ViewHelper;

import cn.aishua.R;

public class UserInfoActivity
    extends Activity
{

    private int year = 2012;
    private int month = 9; // calender month (0-11)
    private int day = 23;

    private EditText etRealName;

    private RadioGroup rgGender;

    private TextView tvBirthDate;

    private Spinner spProvince;
    private Spinner spCity;
    private Spinner spCounty;

    String strProvince;
    String strCity;
    String strCounty;
    String strAddress;

    private EditText etAddress;

    public static final int DIALOG_DATE_PICKR_ID = 0;
    public static final int DIALOG_NAME_INPUT_ID = 1;
    public static final int DIALOG_ADDRESS_INPUT_ID = 2;

    // page header widgets
    private ImageView ivLeftBtn;
    private ImageView ivRightBtn;
    private TextView tvTitile;

    private void initPageHeader()
    {
        // left button
        ivLeftBtn = (ImageView) findViewById( R.id.page_header_iv_left_btn );
        ivLeftBtn.setImageResource( R.drawable.btn_back );
        ivLeftBtn.setOnClickListener( new View.OnClickListener()
        {

            @Override
            public void onClick( View v )
            {
                back();
            }
        } );

        // title
        tvTitile = (TextView) findViewById( R.id.page_header_tv_title );
        tvTitile.setText( "个人资料" );

        // right button
        ivRightBtn = (ImageView) findViewById( R.id.page_header_iv_right_btn );
        ivRightBtn.setImageResource( R.drawable.btn_confirm );
        ivRightBtn.setOnClickListener( new View.OnClickListener()
        {

            @Override
            public void onClick( View v )
            {
                save();
            }
        } );
    }

    @Override
    protected void onCreate( Bundle savedInstanceState )
    {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.my_kaka_user_info );
        initPageHeader();
        initiate();
    }

    public void save()
    {
        String realName = etRealName.getText().toString().trim();
        String gender = ViewHelper.extractText( this, rgGender.getCheckedRadioButtonId() );
        String birthDate = tvBirthDate.getText().toString().trim();
        String province = spProvince.getSelectedItem().toString().trim();
        String city = spCity.getSelectedItem().toString().trim();
        String county = spCounty.getSelectedItem().toString().trim();
        String address = etAddress.getText().toString().trim();

        if( !validateInput( realName, address ) )
        {
            return;
        }

        new DataExchangeAsyncTask( this, "保存用户信息" )
        {
            @Override
            protected HttpResponse sendRequest( String... params )
            {
                return HttpRequestUtil.getInstance().completeUserInfo( params );
            }

            @Override
            protected void handleSuccResponse( String strJson )
            {
                Toast.makeText( UserInfoActivity.this, "已保存个人资料", Toast.LENGTH_SHORT ).show();
                Intent intent = new Intent( UserInfoActivity.this, MainActivityGroup.class );
                intent.putExtra( MainActivityGroup.TAB, MainActivityGroup.TAG_USER_INFO );
                startActivity( intent );
                finish();
            }
        }.execute( realName, province, city, county, gender, birthDate, address );

    }

    private boolean validateInput( String realName, String address )
    {
        if( realName.trim().length() > 8 )
        {
            showDialog( DIALOG_NAME_INPUT_ID );
            return false;
        }
        else if( address.trim().length() > 15 )
        {
            showDialog( DIALOG_ADDRESS_INPUT_ID );
            return false;
        }
        else
        {
            return true;
        }
    }

    public void pickDate( View view )
    {
        showDialog( DIALOG_DATE_PICKR_ID );
    }

    @Override
    protected Dialog onCreateDialog( int id, Bundle bundle )
    {
        Dialog mDialog = null;

        switch( id )
        {
            case DIALOG_DATE_PICKR_ID:
                mDialog = new DatePickerDialog( this, new DatePickerDialog.OnDateSetListener()
                {

                    public void onDateSet( DatePicker view, int year, int monthOfYear, int dayOfMonth )
                    {
                        UserInfoActivity.this.year = year;
                        UserInfoActivity.this.month = monthOfYear;
                        UserInfoActivity.this.day = dayOfMonth;
                        updateDateDisplay();
                    }
                }, year, month, day );
                break;
            case DIALOG_NAME_INPUT_ID:
                mDialog = new AlertDialog.Builder( this ).setMessage( "真实姓名最多允许输入8 个字，请重新输入" )
                    .setNegativeButton( "确定", new OnClickListener()
                    {

                        public void onClick( DialogInterface dialog, int which )
                        {
                            dialog.cancel();
                        }
                    } ).create();
                break;

            case DIALOG_ADDRESS_INPUT_ID:
                mDialog = new AlertDialog.Builder( this ).setMessage( "详细地址最多允许输入15个字，请重新输入" )
                    .setNegativeButton( "确定", new OnClickListener()
                    {

                        public void onClick( DialogInterface dialog, int which )
                        {
                            dialog.cancel();
                        }
                    } ).create();
                break;
            default:
                break;
        }

        return mDialog;
    }

    private void updateDateDisplay()
    {
        tvBirthDate.setText( year + "-" + ( month + 1 ) + "-" + day );
    }

    private void initiate()
    {
        //        copyCityDbFileToSDCard();

        etRealName = (EditText) findViewById( R.id.my_kaka_user_info_et_real_name );

        tvBirthDate = (TextView) findViewById( R.id.my_kaka_user_info_tv_birth_date );
        rgGender = (RadioGroup) findViewById( R.id.my_kaka_user_info_rg_gender );
        spProvince = (Spinner) findViewById( R.id.my_kaka_user_info_sp_province );
        spCity = (Spinner) findViewById( R.id.my_kaka_user_info_sp_city );
        spCounty = (Spinner) findViewById( R.id.my_kaka_user_info_sp_distinct );
        etAddress = (EditText) findViewById( R.id.my_kaka_user_info_et_address );

        // initiate all of these widgets based on extra data of intent
        Intent intent = getIntent();
        etRealName.setText( intent.getStringExtra( MemberCenterActivity.EXTRA_MSG_REAL_NAME ) );

        strProvince = intent.getStringExtra( MemberCenterActivity.EXTRA_MSG_PROVINCE );
        strCity = intent.getStringExtra( MemberCenterActivity.EXTRA_MSG_CITY );
        strCounty = intent.getStringExtra( MemberCenterActivity.EXTRA_MSG_DISTRICT );
        strAddress = intent.getStringExtra( MemberCenterActivity.EXTRA_MSG_ADDRESS );
        String strGender = intent.getStringExtra( MemberCenterActivity.EXTRA_MSG_GENDER );

        if( strGender != null && !"".equals( strGender ) )
        {
            if( "男".equals( strGender ) )
            {
                rgGender.check( R.id.my_kaka_user_info_rb_male );
            }
            else if( "女".equals( strGender ) )
            {
                rgGender.check( R.id.my_kaka_user_info_rb_female );
            }
        }

        initiateDate();

        // residence needs to be divided into three pieces. Now the assumed format is xx省xx市xxxx(具体地址)
        initiateCompleteAddress();

    }

    private void initiateCompleteAddress()
    {
        List<String> provinceList = DatabaseOperator.getInstance().getProvinceList();
        ArrayAdapter<String> adapter1 = new ArrayAdapter<String>( this, R.layout.my_spinner, provinceList );
        adapter1.setDropDownViewResource( R.layout.my_spinner_shake_dropdown );
        spProvince.setAdapter( adapter1 );

        ProvinceSelectedListner listner = new ProvinceSelectedListner();
        listner.setInitialCity( strCity );
        spProvince.setOnItemSelectedListener( listner );
        spProvince.setSelection( getPosition( strProvince, provinceList ) );

        etAddress.setText( strAddress );

    }

    private void initiateDate()
    {
        Intent intent = getIntent();
        String strBirthDate = intent.getStringExtra( MemberCenterActivity.EXTRA_MSG_BIRTH_DATE );
        //  format yyyy-MM-dd
        String[] items = strBirthDate.split( "-" );
        if( items != null && items.length == 3 )
        {
            year = Integer.valueOf( items[0] );
            month = Integer.valueOf( items[1] ) - 1;
            day = Integer.valueOf( items[2] );
        }
        else
        {
            Log.d( "UserInfoActivity", "unparseable date" );
            Calendar today = Calendar.getInstance();
            year = today.get( Calendar.YEAR );
            month = today.get( Calendar.MONTH );
            day = today.get( Calendar.DAY_OF_MONTH );
        }

        tvBirthDate.setText( strBirthDate );
    }

    private int getPosition( String item, List<String> list )
    {
        if( list != null && item != null )
        {
            for( int i = 0; i < list.size(); i++ )
            {
                if( item.equals( list.get( i ) ) )
                {
                    return i;
                }
            }
        }
        return 0;
    }

    class ProvinceSelectedListner
        implements OnItemSelectedListener
    {

        private String initialCity;

        public void onItemSelected( AdapterView<?> container, View view, int index, long id )
        {
            Log.i( getClass().getSimpleName(), "Contianer is: " + container.getClass().getSimpleName() );
            Log.i( getClass().getSimpleName(), "current view is: " + view.getClass().getSimpleName() );
            String provinceName = container.getItemAtPosition( index ).toString();
            List<String> cityList = DatabaseOperator.getInstance().getCityList( provinceName );

            ArrayAdapter<String> adapter = new ArrayAdapter<String>( UserInfoActivity.this, R.layout.my_spinner,
                cityList );
            adapter.setDropDownViewResource( R.layout.my_spinner_shake_dropdown );
            spCity.setAdapter( adapter );

            if( initialCity != null )
            {
                spCity.setSelection( getPosition( initialCity, cityList ) );
                spCity.setOnItemSelectedListener( new CitySelectedListner( strCounty ) );
                initialCity = null;
            }

        }

        public void onNothingSelected( AdapterView<?> arg0 )
        {

        }

        public String getInitialCity()
        {
            return initialCity;
        }

        public void setInitialCity( String initialCity )
        {
            this.initialCity = initialCity;
        }

    }

    class CitySelectedListner
        implements OnItemSelectedListener
    {

        private String inisitalCounty;

        public CitySelectedListner(String initialCounty)
        {
            this.inisitalCounty = initialCounty;
        }

        public void onItemSelected( AdapterView<?> container, View view, int index, long id )
        {
            String cityName = container.getItemAtPosition( index ).toString();
            List<String> countyList = DatabaseOperator.getInstance().getCountyList( cityName );

            if( countyList.size() == 0 ) // if there is no county for this city selected, spinner should be unable
            {
                spCounty.setEnabled( false );
                spCounty.setClickable( false );
            }
            else
            {
                spCounty.setEnabled( true );
                spCounty.setClickable( true );

                ArrayAdapter<String> adapter = new ArrayAdapter<String>( UserInfoActivity.this, R.layout.my_spinner,
                    countyList );
                adapter.setDropDownViewResource( R.layout.my_spinner_shake_dropdown );
                spCounty.setAdapter( adapter );
                spCounty.setSelection( getPosition( inisitalCounty, countyList ) );
            }
        }

        public void onNothingSelected( AdapterView<?> arg0 )
        {

        }

    }

    public void back()
    {
        Log.d( "UserInfoActivity", "back()" );
        new AlertDialog.Builder( this ).setTitle( "放弃修改个人资料？" ).setMessage( null )
            .setPositiveButton( "确定", new OnClickListener()
            {

                public void onClick( DialogInterface dialog, int which )
                {
                    Log.d( "AlertDialog", "positive button: onClick()" );

                    UserInfoActivity.this.onBackPressed();
                }
            } ).setNegativeButton( "取消", null ).show();
    }

}
